package common;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtils {
	public static List<String> getMatches(CharSequence input, String regex) {
		if (input == null) return null;
		List<String> matches = new ArrayList<String>();
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		while (matcher.find()) {
			matches.add(matcher.group());
		}
		return matches;
	}

	public static String[] getGroups(CharSequence input, String regex) {
		if (input == null) return null;
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		if (matcher.find()) {
			String[] data = new String[matcher.groupCount()];
			for (int i = 0; i < matcher.groupCount(); i++) {
				data[i] = matcher.group(i + 1);
			}
			return data;
		}
		return new String[]{String.valueOf(input)};
	}

	public static String getByJson(String key, String json) {
		String regex1 = key + "\":\"(.*?)\"";
		String regex2 = key + "\":(.*?)(,|})";
		Matcher matcher ;
		if ((matcher = Pattern.compile(regex1).matcher(json)).find() || (matcher = Pattern.compile(regex2).matcher(json)).find()) {
			try {
				return matcher.group(1);
			}catch (Exception e){
				return "";
			}
		}
		return "";
	}

	public static String getByDoc(String regex, String content) {
		return getByDoc(regex, content, 1);
	}

	public static String getByDoc(String regex, String content, int group) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
		if (matcher.find()) {
			try {
				return matcher.group(group);
			}catch (Exception e){
				return "";
			}
		}
		return "";
	}

	public static String getByDocAll(String regex, String content, int group) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()){
			sb.append(";");
			sb.append(matcher.group(group));
		}
		return sb.length()>0?sb.substring(1):"";
	}
}
